<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 */

require_once ('MDB2.php');

/**
 *
 * @author "Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>"
 *
 */
class MDB2_DAO extends DAO
{

  const IDENTIFIER_PATTERN = '/\{[a-zA-Z0-9_]+(( |\.)[a-zA-Z0-9_]+)*\}/';

  /**
   *
   * @var MDB2_Driver_Common
   */
  private $mdb2;

  /**
   *
   * @var array
   */
  protected $dsn;

  /**
   *
   * @var array
   */
  protected $options;

  /**
   * Constructor.
   *
   * @param array $params
   * @return void
   */
  protected function __construct($params)
  {
    parent::__construct($params);

    $this->dsn = array(
      'phptype' => $this->params->get('type', 'mysql'),
      'username' => $this->params->get('username'),
      'password' => $this->params->get('password'),
      'hostspec' => $this->params->get('host', 'localhost'),
      'database' => $this->params->get('name'),
      'charset' => $this->params->get('charset', 'utf8')
    );

    $this->options = array(
      'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL
    );
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/dao/DAO#db()
   * @return MDB2_Driver_Common
   */
  public function db()
  {
    return $this->connect()->mdb2;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/dao/DAO#connect()
   */
  public function connect()
  {
    if (empty($this->mdb2)) {
      $this->mdb2 = MDB2::connect($this->dsn, $this->options);

      if (PEAR::isError($this->mdb2)) {
        throw new Exception($this->mdb2->getUserInfo());
      }

      $this->mdb2->fetchmode = MDB2_FETCHMODE_ASSOC;
    }
    else {
      $this->mdb2->connect();
    }

    return $this;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/dao/DAO#disconnect()
   */
  public function disconnect()
  {
    if ($this->mdb2 && ! PEAR::isError($this->mdb2)) {
      $this->mdb2->disconnect();
    }

    return $this;
  }

  /**
   *
   * @param $table
   * @return MDB2_QueryObject
   */
  public function from($table)
  {
    $q = new MDB2_QueryObject($this);
    return $q->from($table);
  }

  /**
   *
   * @param $sql
   * @return MDB2_QueryObject
   */
  public function query($sql)
  {
    $q = new MDB2_QueryObject($this);
    return $q->query($sql);
  }

  /**
   * Get last inserted ID
   *
   * @return mixed
   */
  public function lastInsertID()
  {
    $return = $this->db()->lastInsertID();
    MDB2_DAO::validate($return);
    return $return;
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/dao/DAO#create($o)
   */
  protected function create(Entity $o)
  {
    $data = $o->getModified();

    $def = $o->getDefinition();

    $table = $o->getName();

    $fields = array();
    $values = array();
    $types = array();

    foreach ($def->getFields() as $name => $field) {
      if (! isset($data[$name])) {
        continue;
      }

      $fields[] = '{' . $table . '.' . $name . '}';
      $values[] = DataMapper::deflateValue($data[$name], $field->getType());
      $types[] = $field->getType();
    }

    $v = implode(', ', str_split(str_repeat('?', count($fields))));
    $sql = sprintf('INSERT INTO {%s} (%s) VALUES (%s)', $table, implode(', ', $fields), $v);

    $sql = MDB2_DAO::processQuery($sql, $this->config);

    $stmt = $this->db()->prepare($sql, $types, MDB2_PREPARE_MANIP);
    MDB2_DAO::validate($stmt);

    $resp = $stmt->execute($values);
    MDB2_DAO::validate($resp);

    $stmt->free();

    parent::create($o);
  }

  /**
   * (non-PHPdoc)
   * @see simplify/kernel/dao/DAO#update($o)
   */
  protected function update(Entity $o)
  {
    $data = $o->getModified();

    $def = $o->getDefinition();

    $table = $o->getName();

    $fields = array();
    $values = array();
    $types = array();

    $pk = $def->getPrimaryKey();

    foreach ($def->getFields() as $name => $field) {
      if (! isset($data[$name]) || $name == $pk) {
        continue;
      }

      $fields[] = '{' . $table . '.' . $name . '} = ?';

      $values[] = DataMapper::deflateValue($data[$name], $field->getType());

      $types[] = $field->getType();
    }

    $sql = sprintf('UPDATE {%s} SET %s WHERE {%1$s.%s} = ?', $table, implode(', ', $fields), $pk);

    $values[] = $o->$pk;

    $sql = MDB2_DAO::processQuery($sql, $this->config);

    $stmt = $this->db()->prepare($sql, $types, MDB2_PREPARE_MANIP);
    MDB2_DAO::validate($stmt);

    $resp = $stmt->execute($values);
    MDB2_DAO::validate($resp);

    $stmt->free();

    parent::update($o);
  }

  /**
   * Check if $res is MDB2_Error
   *
   * @param mixed $res
   * @throws Exception if any errors ocurred
   * @return void
   */
  public static function validate($res, $info = null)
  {
    if (PEAR::isError($res)) {
      $msg = $res->getUserInfo();

      if (preg_match('/\[Native message: ([^\]]*)\]/', $msg, $o)) {
        $msg = $o[1];
      }
      else if (preg_match('/\[Error message: ([^\]]*)\]/', $msg, $o)) {
        $msg = $o[1];
      } /* else {
        $msg = $res->getMessage();
      }*/

      if (! empty($info)) {
        $info = "\n\n" . implode("\n\n", (array)$info);
      }

      throw new Exception($msg . $info);
    }
  }

  /**
   *
   * @param string $table
   * @return EntityDefinition
   */
  public function reverseEntityDefinition($table, $name)
  {
    $def = new MDB2_ReverseEntityDefinition($this->db(), $table);
    $this->addEntity($name, $def);
    return $def;
  }

  /**
   *
   * @param string $q
   * @param string $class
   * @param string $alias
   * @param DomainDefinition $config
   * @return string
   */
  public static function processSubQuery($q, $class, $alias, DomainDefinition $config)
  {
    preg_match_all(self::IDENTIFIER_PATTERN, $q, $matches, PREG_SET_ORDER);

    foreach ($matches as $key => $m) {
      // clear braces
      $str = substr($m[0], 1, - 1);

      $propconf = $config->getEntity($class)->getField($str);

      $q = str_replace($m[0], $alias . '.' . $propconf[0], $q);
    }

    return $q;
  }

  /**
   *
   * @param string $q
   * @param DomainDefinition $config
   * @return string
   */
  public static function processQuery($q, DomainDefinition $config)
  {
    preg_match_all(self::IDENTIFIER_PATTERN, $q, $matches, PREG_SET_ORDER);

    // check if it's an update statement
    $update = (stripos(trim($q), 'UPDATE') === 0);

    // get the table names
    $aliased = array();
    foreach ($matches as $key => $m) {
      // clear braces
      $str = substr($m[0], 1, - 1);

      // if it's an aliased class
      if (strpos($str, ' ') !== false) {
        $tmp = explode(' ', $str);
        $aliased[$tmp[1]] = $tmp[0];

        $q = str_replace($m[0], $config[$tmp[0]]->getTable() . ' ' . $tmp[1], $q);
      }

      // if it's a non-aliased class
      elseif (strpos($str, '.') === false) {
        // if it's a non-aliased class
        $table = $config->getEntity($str)->getTable();
        $aliased[$table] = $str;
        $q = str_replace($m[0], $table, $q);
      }
    }

    // update references to the properties
    foreach ($matches as $key => $m) {
      // clear braces
      $str = substr($m[0], 1, - 1);

      // if it's a property
      if (strpos($str, '.') !== false) {
        list($en, $prop) = explode('.', $str);

        // if it's an alias
        if (isset($aliased[$en])) {
          $entity = $aliased[$en];
          $alias = $en;
        }
        else {
          $entity = $en;
          $alias = $config->getEntity($entity)->getTable();
        }

        $propconf = $config->getEntity($entity)->getField($prop);

        // if it's an update statement,
        // we must not include the table
        if ($update) {
          // skip if it's an sql field
          if (! $propconf->getSql()) {
            $col = $propconf->getName();
          }
        }
        else {
          // if it's an sql field
          if ($propconf->getSql()) {
            $col = '(' . MDB2_DAO::processSubQuery($propconf->getSql(), $entity, $alias) . ')';
          }

          else {
            $col = $alias . '.' . $propconf->getName();
          }
        }

        $q = str_replace($m[0], $col, $q);
      }
    }

    return $q;
  }

}

?>